#!/bin/bash

# Usage info
show_help() {
    cat << EOF
Usage: ${0##*/} [-h] [-p PORT] [-r]
Run datatracker in dev containers using docker-compose.

    -h          display this help and exit
    -p PORT     use custom HTTP port for datatracker
    -r          force rebuild the app container

EOF
}

CUSTOM_PORT=8000
FORCE_REBUILD=0

while getopts "hp:r" opt; do
    case $opt in
        h)
            show_help
            exit 0
            ;;
        p)  
            CUSTOM_PORT=$OPTARG
            echo "Using custom port $CUSTOM_PORT..."
            ;;
        r)
            FORCE_REBUILD=1
            echo "Will force rebuild the app container..."
            ;;
        *)
            CUSTOM_PORT=8000
            echo "Using port 8000..."
            ;;
    esac
done

# Ensure the run script is in our directory.
dirname=$(dirname $0)
if [ "$dirname" = "." -o "$dirname" = "" ] ; then
    :
else
    echo "Changing to directory $dirname"
    cd $dirname || exit 1
fi

# Remove mounted temp directories
rm -rf .parcel-cache __pycache__

# Create extended docker-compose definition
sed -e "s/CUSTOM_PORT/$CUSTOM_PORT/" \
	<docker-compose.extend.yml \
	>docker-compose.extend-custom.yml
cd ..

# Set UID/GID mappings
NEW_UID=$(id -u)
NEW_GID=$(id -g)
if [ $NEW_UID -gt 0 ]; then
    echo "Will use the following user/group mapping:"
    echo "USER ID: $NEW_UID"
    echo "GROUP ID: $NEW_GID"
else
    echo "Running as root, will use default user/group mapping..."
    echo "NOT RECOMMENDED - You may experience permission issues."
    NEW_UID=1000
    NEW_GID=1000
fi

# Build / Rebuild Containers
if [ $FORCE_REBUILD ==  1 ]; then
    docker compose -f docker-compose.yml -f docker/docker-compose.extend-custom.yml down
    docker compose -f docker-compose.yml -f docker/docker-compose.extend-custom.yml rm -f
    docker compose -f docker-compose.yml -f docker/docker-compose.extend-custom.yml build --no-cache --pull --build-arg USER_UID=$NEW_UID --build-arg USER_GID=$NEW_GID
    docker compose -f docker-compose.yml -f docker/docker-compose.extend-custom.yml up -d --force-recreate
else
    docker compose -f docker-compose.yml -f docker/docker-compose.extend-custom.yml build --build-arg USER_UID=$NEW_UID --build-arg USER_GID=$NEW_GID
    docker compose -f docker-compose.yml -f docker/docker-compose.extend-custom.yml up -d
fi

# Output database port
echo "Database exposed on port:"
docker compose port db 3306

# Start init script
docker compose exec app /bin/zsh /docker-init.sh

# Exit scripts
docker compose stop
cd docker
rm -f docker-compose.extend-custom.yml
